<template>
    <a-card title="基本信息" class="add_edit_product">
        <a-form :label-col="{ span: 3 }" :wrapper-col="{ span: 20 }">            
            <div class="title">商品信息：</div>
            <a-form-item>
                <template slot="label">
                    <span style="color: red">*</span>商品类型
                </template>
                <a-radio-group v-model="formData.productType" :options="productTypeList"></a-radio-group>
            </a-form-item>
            <a-form-item>
                <template slot="label">
                    <span style="color: red">*</span>商品名称
                </template>
                <a-input placeholder="输入商品名称" :maxLength="60" v-model="formData.productName" style="width:200px"/>
            </a-form-item>
            <a-form-item label="商品编码">
                <a-space>
                    <a-input placeholder="输入商品编码" :maxLength="60" v-model="formData.productCode" style="width:200px"/>
                    <!-- <div class="desc">不填写系统生成</div> -->
                </a-space>
            </a-form-item>
            <a-form-item>
                <template slot="label">
                    <span style="color: red">*</span>商品分类
                </template>
                <a-space>
                    <!-- <a-select placeholder="请选择" v-model="formData.productClassify" allowClear :options="commodityGroupList" style="width:200px"></a-select> -->
                    <a-tree-select
                        allowClear
                        style="width:200px"
                        :replaceFields="{children:'children', title:'classifyName', key:'id', value: 'id' }"
                        v-model="formData.productClassify"
                        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                        :tree-data="commodityClassifyList"
                        placeholder="请选择"
                        tree-default-expand-all
                        >
                        <span slot="title" slot-scope="{ value }">
                            {{ value }}
                        </span>
                    </a-tree-select>
                    <a href="javascript:;" @click="productClassifyShow=true">新建分类</a>
                    |
                    <a href="javascript:;" @click="handleRefreshProductClassify">刷新</a>
                </a-space>
                <div class="desc">商品分类用于店铺内部经营管理与财务利润核算</div>
            </a-form-item>
            <a-form-item>
                <template slot="label">
                    <span style="color: red">*</span>商品类目
                </template>
                <a-space>
                    <a-tree-select
                        allowClear
                        style="width:200px"
                        :replaceFields="{children:'children', title:'categoryName', key:'id', value: 'id' }"
                        v-model="formData.productCategory"
                        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                        :tree-data="commodityCategoryList"
                        placeholder="请选择"
                        tree-default-expand-all
                        :disabled="shopType==2 && id!=''"
                        >
                        <span slot="title" slot-scope="{ value }">
                            {{ value }}
                        </span>
                    </a-tree-select>
                </a-space>
                <div class="desc">准确选择商品类目有助于完善商品信息与数据分析。商品类目及类目细项</div>
            </a-form-item>
            <a-form-item label="商品卖点">
                <a-textarea placeholder="请输入" style="width:500px" :maxLength="60" v-model="formData.productPoints"></a-textarea>
                <div class="desc">在商品详情页标题下面展示卖点信息，建议 60 字以内</div>
            </a-form-item>
            <a-form-item>
                <template slot="label">
                    <span style="color: red">*</span>商品图片
                </template>
                <ImageUploadList
                  :limit="15"
                  :multiple="true"
                  :value="formData.imgList"
                  @change="handleProductImageChange">
                </ImageUploadList>
                <div class="desc">建议尺寸：640 x 640 像素；你可以拖拽图片调整图片顺序。最多上传15张</div>
            </a-form-item>
            <a-form-item label="商品视频">
                <UploadFileList
                  :limit="1"
                  :multiple="false"
                  :value="formData.videoList"
                  accept=".mp4"
                  @change="handleProductVideoChange">
                </UploadFileList>
                <div class="desc">视频不能超过10M，支持mp4视频格式</div>
            </a-form-item> 
            <a-form-item label="库存单位">
                <a-select v-model="formData.inventoryUnit" class="width200" :options="inventoryUnitList"></a-select>
            </a-form-item>
            <a-form-item label="分享描述">
                <a-textarea placeholder="请输入" v-model="formData.shareDescribe" style="width:500px" :maxLength="32"></a-textarea>
                <div class="desc">微信分享给好友时会显示，建议32个字以内</div>
            </a-form-item>
            <a-form-item label="虚拟销量">
                <a-input type="number" placeholder="可不填写，请填写虚拟销量" v-model="formData.virtualSales" style="width:200px"/>
            </a-form-item>

            <div class="title">商品规格信息：</div>
            <a-form-item>
                <template slot="label">
                    <span style="color: red">*</span>商品型号
                </template>
                <a-radio-group :options="commodityModelList" v-model="formData.productModel" style="width:200px;" @change="handleProductModelSwitch"/>
            </a-form-item>
            <template v-if="formData.productModel==1">
                <a-form-item>
                    <template slot="label">
                        <span style="color: red">*</span>商品库存
                    </template>
                    <a-space>
                        <a-input-number  :precision="0" type="number" :disabled="shopType==2 && id!=''" placeholder="请填写商品库存" v-model="formData.productSpecList[0].goodsInventory" :min="0" :max="99999999" style="width:130px;"/>
                        件
                    </a-space>
                </a-form-item>
                <a-form-item>
                    <template slot="label">
                        <span style="color: red">*</span>商品预警
                    </template>
                    <a-space>
                        <a-input-number type="number" placeholder="请输入预警数量" v-model="formData.productWarning" :maxLength="9" :precision="0"  :min="0" :max="99999999" style="width:130px;"/>
                        件
                    </a-space>
                </a-form-item>
                <a-form-item label="ERP编码">
                    <a-input placeholder="选填 用于商家系统对接" v-model="formData.productSpecList[0].erpCode" :maxLength="60" style="width:200px;"/>
                </a-form-item>
                <a-form-item label="商品重量">
                    <a-input-number :precision="2" type="number" placeholder="请输入商品重量" v-model="formData.productSpecList[0].goodsWeight" :min="0" :max="99999999" style="width:200px;"/>
                </a-form-item>
                <a-form-item>
                    <a-col :offset="2">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th><span class="color_red">*</span>市场价格（划线价）</th>
                                    <th><span class="color_red">*</span>销售价格</th>
                                    <th><span class="color_red">*</span>分销价格</th>
                                    <th>一级分销价格</th>
                                    <th>二级分销价格</th>
                                    <th>三级分销价格</th>
                                    <th>供货商</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td><a-input-number placeholder="请输入" v-model="formData.productSpecList[0].marketPrice" :precision="2" :min="0" :max="99999999" /> (元)</td>
                                    <td><a-input-number placeholder="请输入" v-model="formData.productSpecList[0].salePrice" :precision="2" :min="0" :max="99999999" /> (元)</td>
                                    <td><a-input-number placeholder="请输入" v-model="formData.productSpecList[0].rebatePrice" :precision="2" :min="0" :max="99999999" /> (元)</td>
                                    <td><a-input-number placeholder="请输入" v-model="formData.productSpecList[0].oneLevelDistributionPrice" :precision="2" :min="0" :max="99999999" /> (元)</td>
                                    <td><a-input-number placeholder="请输入" v-model="formData.productSpecList[0].twoLevelDistributionPrice" :precision="2" :min="0" :max="99999999" /> (元)</td>
                                    <td><a-input-number placeholder="请输入" v-model="formData.productSpecList[0].threeLevelDistributionPrice" :precision="2" :min="0" :max="99999999" /> (元)</td>
                                    <td><a-input-number placeholder="请输入" v-model="formData.productSpecList[0].supplierPrice" :precision="0" :min="0" :max="99999999" /></td>
                                </tr>
                            </tbody>
                        </table>
                    </a-col>
                </a-form-item>
            </template>
            <template v-if="formData.productModel==2">
                <a-form-item>
                    <template slot="label">
                        <span style="color: red">*</span>商品预警
                    </template>
                    <a-space>
                        <a-input-number :precision="0" :min="0" :max="99999999" type="number" placeholder="请输入预警数量" v-model="formData.productWarning"  style="width:130px;"/>
                        件
                    </a-space>
                </a-form-item>
                <a-form-item class="model">
                    <MultiModel :data="multiModelData" @change="handleTableChange"></MultiModel>
                </a-form-item>
            </template>

            <div class="title">物流信息：</div>
            <a-form-item>
                <template slot="label">
                    <span style="color: red">*</span>发货仓库
                </template>
                <a-select style="width:200px;" :options="deliveryWarehouseList" v-model="formData.deliveryWarehouseId"></a-select>
            </a-form-item>
            <a-form-item>
                <template slot="label">
                    <span style="color: red">*</span>配送方式
                </template>
                <a-space>
                    <a-checkbox-group :options="deliveryModeList" v-model="formData.deliveryMode"></a-checkbox-group>
                    <!-- <a href="javascript:;" v-if="formData.deliveryMode.includes(2)" @click="selfExtractionShow=true">请选择自提地址</a> -->
                </a-space>
                <!-- <div>
                    <a-table bordered :data-source="selfExtractionTableData" :columns="selfExtractionTableColumns" :pagination="false" :rowKey="record=>record.id">
                        <template slot="operation" slot-scope="text, record, index">
                            <a href="javascript:;" class="delete" @click="handleRemoveAddress(index)">移除</a>
                        </template>
                    </a-table>
                </div> -->
            </a-form-item>
            <div class="title">渠道设置：</div>
            <a-form-item label="店铺发布渠道">
                <a href="javascript:;" @click="shopShow=true;">
                    <template v-if="formData.shopIdList.length>0">
                        重新选择店铺
                    </template>
                    <template v-else>
                        选择店铺
                    </template>
                </a>
            </a-form-item>
            <div class="title">商品详情：</div>
            <a-form-item>
                <a-col :offset="2">
                    <tinymce-editor v-model="formData.productInfo"></tinymce-editor>
                </a-col>
            </a-form-item>
            <a-form-item>
                <a-col :offset="2">
                    <a-space>
                        <a-button @click="handleCancel">取消</a-button>
                        <a-button type="primary" @click="submitData()">提交保存</a-button>
                        <!-- <a-button @click="handlePreview">预览</a-button> -->
                    </a-space>
                </a-col>
            </a-form-item>
        </a-form>
        <!-- <CommodityLibrary :visible="commodityLibShow" @cancel="commodityLibShow=false" @submit="handleSelectedCommodityLibrary"></CommodityLibrary> -->
        <ShopList :visible="shopShow" :shopIds="formData.shopIdList" @cancel="shopShow=false;" @submit="handleShopSubmit"></ShopList>
        <ProductClassify :visible="productClassifyShow" @cancel="handleProductClassifyCancel"></ProductClassify>
        <FreightTemplate :visible="freightTemplateShow" @cancel="handleFreightTemplateCancel"></FreightTemplate>
        <SelfExtraction :visible="selfExtractionShow" @cancel="SelfExtraction=false"></SelfExtraction>
        <ProductPreview :data="formData" :visible="previewShow" @cancel="previewShow=false"></ProductPreview>
    </a-card>
</template>

<script>
import deepCopy from '@/utils/deepCopy'
//import ImageUploadList from '@/components/form/UploadImage'
import ImageUploadList from './components/UploadImage'
import UploadFileList from '@/components/form/UploadFile'
import ImageUpload from '@/components/antBase/ImageUpload'
//import CommodityLibrary from './components/CommodityLibrary';
import ShopList from '@/components/ShopList/ShopList';
import ProductClassify from './components/ProductClassify';
import FreightTemplate from './components/FreightTemplate';
import MultiModel from './components/MultiModel';
import SelfExtraction from './components/SelfExtraction';
import ProductPreview from './components/ProductPreview';

const productSpecList=[
    {
        id:'',	//商品规格id
        goodsInventory:'',	//商品库存数量
        erpCode:'',	//erp编码
        goodsWeight:'',	//商品重量（单位：g 克）
        marketPrice:'',	//市场价格（划线价，单位：分）
        salePrice:'',	//销售价格（单位：分）
        rebatePrice:'',	//返利价格（单位：分）
        oneLevelDistributionPrice:'',	//一级分销价格（单位：分）
        twoLevelDistributionPrice:'',	//二级分销价格（单位：分）
        threeLevelDistributionPrice:'',	//三级分销价格（单位：分）
        //superiorModelIds:'',	//上级商品型号分类id多个,隔开
        //modelIds:1,	//商品型号id,多个以,隔开
        modelPicture:'',	//商品型号图片
        superiorModelIds:'',
        modelIds:'',
    }
]
// const modelData=[
//     {
//         modelClassifyId:'',
//         isAddImg:true,
//         modelList:[
//             // {
//             //     label:'测试1',
//             //     value:'1',
//             // },
//             // {
//             //     label:'测试2',
//             //     value:'2',
//             // }
//         ]
//     }
// ]
const formData={
    productLibId:'',//商品库id，引入商品库商品编码不可编辑
    //商品信息
    productType:2,//商品类型
    productName:'',//商品名称
    productCode:'',//商品编码
    productClassify:'',//商品分类
    productGroup:'',//商品分组
    productCategory:'',//商品类目
    productPoints:'',//商品卖点
    imgList:'',//商品图片
    videoList:'',//商品视频
    inventoryUnit:'',//库存单位
    shareDescribe:'',//分享描述
    virtualSales:'',//虚拟销量

    //商品规格信息
    productModel:1,//商品型号
    productWarning:'',
    productUnitCode:'',//商品库存
    productSpecList:deepCopy(productSpecList),
    productMultiSpecList:[],

    //物流信息
    deliveryWarehouse:'',//返货仓库
    deliveryMode:[],//配送方式
    unifiedFreight:'',//统一运费
    storeReleaseChanne:1,//店铺发布渠道
    productInfo:'',//商品详情

    //goodsBrandId:'',//品牌id
    shopIdList:[],//渠道发布店铺id集合

    //多级型号
    freightType:1,//快递运费
    freightTemplateId:'',//运费模板id
    //modelData:deepCopy(modelData),
    deliveryWarehouseId:'',//发货仓库（供应商）

    // productAscription:1,//商品所属
    // supplyGoods:'',//商品所属供应商
    // buyPoints:1,//购买商品积分
    // pointsType:1,//积分类型[1固定积分，2商品价格的百分比]
    // fixedIntegral:'',//固定积分
    // percentage:'',//百分比积分
    // isAllowFullDeduction:1,//是否允许抵扣全额
    // maxFullDeduction:'',//最大抵扣全额
}

export default {
    components:{
        ImageUploadList,
        UploadFileList,
        ImageUpload,
        //CommodityLibrary,
        ShopList,
        ProductClassify,
        FreightTemplate,
        MultiModel,
        SelfExtraction,
        ProductPreview,
    },
    computed:{
        id(){
            return this.$route.query.id || '';
        },
        userInfo(){
            return this.$store.getters.userInfo || {};
        },
        shopId(){
            return this.userInfo.shopId || '';
        },
        shopType(){
            return this.userInfo.userStatus || '';
        }//:1,//总店1；分店2；供应商3
    },
    data(){
        return {
            shopShow:false,//店铺
            productModelShow:false,//商品型号
            productClassifyShow:false,//添加商品类型
            //commodityLibShow:false,
            freightTemplateShow:false,//运费模板
            //shopType:1,//总店1；分店2；供应商3
            //商品类型
            productTypeList:[
                {
                    label:'定制品',
                    value:1
                },{
                    label:'标品',
                    value:2
                }                
            ],
            //商品分类
            commodityClassifyList:[],
            //商品分组
            commodityGroupList:[],
            //商品类目
            commodityCategoryList:[],
            //商品型号
            commodityModelList:[
                {
                    label:'统一型号',
                    value:1
                },
                {
                    label:'多级型号',
                    value:2
                }
            ],
            //配送方式
            deliveryModeList:[
                {
                    label:'快递发送',
                    value:1
                },{
                    label:'到店自提',
                    value:2
                }
            ],
            //快递运费
            expressFreightList:[
                {
                    label:'统一运费',
                    value:1
                },
                // {
                //     label:'运费模板',
                //     value:2
                // }
            ],
            //运费模板
            freightTemplateList:[
                {
                    label:'测试',
                    value:1
                },{
                    label:'测试2',
                    value:2
                }
            ],
            //库存单位
            inventoryUnitList:[
                {
                    label:'件',
                    value:1,
                },
                // {
                //     label:'箱',
                //     value:2
                // },
                // {
                //     label:'口',
                //     value:3
                // }
            ],
            //型号分类
            modelClassifyList:[
                // {
                //     label:'颜色',
                //     value:1
                // },{
                //     label:'颜色2',
                //     value:2
                // }
            ],
            //发货仓库
            deliveryWarehouseList:[],
            formData,
            //多级型号
            multiModelData:[],
            //商品所属
            // productAscriptionList:[
            //     {
            //         label:'自营商品',
            //         value:1
            //     },{
            //         label:'供应商品',
            //         value:2
            //     }
            // ],
            // //供应商品列表
            // supplyGoodsList:[],
            // //购买商品积分
            // pointsList:[
            //     {
            //         label:'否',
            //         value:1
            //     },{
            //         label:'是',
            //         value:2
            //     }
            // ],
            // //抵扣全额列表
            // fullDeductionList:[
            //     {
            //         label:'否',
            //         value:1,
            //     },{
            //         label:'是',
            //         value:2
            //     }
            // ],
            // //自提
            // selfExtractionShow:false,
            // selfExtractionTableData:[],
            // selfExtractionTableColumns:[
            //     {
            //         title:'编号',
            //         key:'a',
            //         dataIndex:'a',
            //     },
            //     {
            //         title:'地址名称',
            //         key:'b',
            //         dataIndex:'b',
            //     },
            //     {
            //         title:'地址类型',
            //         key:'c',
            //         dataIndex:'c',
            //     },
            //     {
            //         title:'联系人姓名',
            //         key:'d',
            //         dataIndex:'d',
            //     },
            //     {
            //         title:'地址',
            //         key:'e',
            //         dataIndex:'e',
            //     },
            //     {
            //         title:'联系电话',
            //         key:'f',
            //         dataIndex:'f',
            //     },
            //     {
            //         title:'操作',
            //         scopedSlots: { customRender: 'operation' }
            //     }
            // ],
            //预览
            previewShow:false,
        }
    },
    watch:{
        
    },
    created(){
        this.resetData();
        console.log('this.userInfo',this.userInfo)
        this.getClassifyList();
        this.getProductCategory();  
        this.getProductGroup();
        this.getFreightTemplate();
        //this.getModelClassifyList();
        this.getDeliveryWarehouseList();
        //供应商列表
        //this.getSupplierList();

        if(this.id){
            this.getProductInfo(this.id);
        }
        //分店调用详情
        // this.$get('/supplier/id',{id:'439112016452386816'}).then(res=>{
        //     console.log('=======================================',res.dataInfo)
        // })
    },
    methods:{
        //回退
        handleCancel(){
            this.$router.push({
                name:'ProductCommodityManageCommodityLibrary'
            })
        },
        //预览
        handlePreview(){
            this.previewShow=true;
        },
        //获取供应商列表
        // async getSupplierList(){
        //     let res=await this.$get('/supplier/type/list');
        //     this.supplyGoodsList=[];
        //     if(res && res.returnCode=='1000'){
        //         (res.dataInfo || []).forEach(item=>{
        //             this.supplyGoodsList.push({
        //                 label:item.typeName,
        //                 value:item.id,
        //             });
        //         })
        //     }
        // },
        //移出自提地址
        // handleRemoveAddress(index){

        // },
        //选择店铺提交
        handleShopSubmit(data){
            console.log(data);
            this.formData.shopIdList=data;
            this.shopShow=false;
        },
        //获取发货仓库（供应商）
        async getDeliveryWarehouseList(){
            let res=await this.$get('/supplier/page',{
                current:1,
                size:100,
            });
            if(res && res.returnCode=='1000'){
                let deliveryWarehouseList=(res.dataInfo||[]).records || [];
                let tmpData=[];
                deliveryWarehouseList.forEach(item=>{
                    tmpData.push({
                        value:item.id, 
                        label:item.supplierName,
                    })
                });
                this.deliveryWarehouseList=tmpData;
            }
        },
        
        //关闭分类弹框
        handleProductClassifyCancel(){
            this.productClassifyShow=false;
            this.handleRefreshProductClassify();
        },
        //刷新分类
        handleRefreshProductClassify(){
            this.getClassifyList();
        },
        //关闭运费模板弹框
        handleFreightTemplateCancel(){
            this.freightTemplateShow=false;
            this.handleRefreshFreightTemplate();
        },
        //刷新运费模板
        handleRefreshFreightTemplate(){
            this.getFreightTemplate();
        },
        //重置
        resetData(){
            this.formData=deepCopy(formData);
        },
        //获取分类列表
        async getClassifyList(){
            let res=await this.$get('/goods/classify/tree',{
                shopId:this.userInfo.shopId || ''
            })
            if(res && res.returnCode=='1000'){
                this.commodityClassifyList=res.dataInfo;
            }
        },
        //获取商品分组
        async getProductGroup(){
            let res=await this.$get('/goods/group/tree',{
                shopId:this.userInfo.shopId || ''
            });
            if(res && res.returnCode=='1000'){
                this.commodityGroupList=res.dataInfo || [];
            }
            else {
                this.commodityGroupList=[];
            }
        },
        //获取商品类目
        async getProductCategory(){
            let res=await this.$get('/goods/category/tree',{
                categoryStatus:1
            });
            if(res && res.returnCode=='1000'){
                this.commodityCategoryList=res.dataInfo || [];
            }
            else {
                this.commodityCategoryList=[];
            }
        },
        //获取运费模板
        async getFreightTemplate(){
            let res=await this.$get('/fare/model/page',{
                current:1,
                size:100,
            });
            if(res && res.returnCode=='1000'){
                console.log('freightTemplateList',res.dataInfo.records)
                let dataInfo=(res.dataInfo || {}).records || [];
                let tmpData=[];
                dataInfo.forEach(item=>{
                    tmpData.push({
                        value:item.id,
                        label:item.fareName
                    })
                })
                this.freightTemplateList=tmpData;
            }
            else {
                this.freightTemplateList=[];
            }
        },
        //商品图片选择
        handleProductImageChange(urls){
            console.log('urls',urls)
            this.formData.imgList=urls;
        },
        //商品视频选择    
        handleProductVideoChange(urls){
            console.log('urls',urls)
            this.formData.videoList=urls;
        },
        //商品型号切换
        handleProductModelSwitch(){
            console.log(this.formData.productModel);
            //this.formData.productSpecList=deepCopy(productSpecList);
            //this.formData.productWarning='';
        },
        //获取商品信息
        async getProductInfo(id){
            let res=await this.$get('/goods/repository/query',{
                id 
            });
            if(res && res.returnCode=='1000'){
                let dataInfo=res.dataInfo || {};
                if(!dataInfo || dataInfo.goodsSpecList.length==0){
                    if(dataInfo.goodsModel==1){
                        dataInfo.goodsSpecList=[
                            {
                                goodsInventory:'',	//商品库存数量
                                erpCode:'',	//erp编码
                                goodsWeight:'',	//商品重量（单位：g 克）
                                marketPrice:'',	//市场价格（划线价，单位：分）
                                salePrice:'',	//销售价格（单位：分）
                                rebatePrice:'',	//返利价格（单位：分）
                                oneLevelDistributionPrice:'',	//一级分销价格（单位：分）
                                twoLevelDistributionPrice:'',	//二级分销价格（单位：分）
                                threeLevelDistributionPrice:'',	//三级分销价格（单位：分）
                                superiorModelIds:'',	//上级商品型号分类id多个,隔开
                                modelIds:'',	//商品型号id,多个以,隔开
                                modelPicture:'',	//商品型号图片
                            }
                        ]
                    }
                }
                let deliveryMode=dataInfo.deliveryMode || '';
                if(deliveryMode){
                    console.log('deliveryMode',deliveryMode,deliveryMode.split(','))
                    deliveryMode=deliveryMode.split(',').map(item=>parseFloat(item));
                }
                else {
                    deliveryMode=[];
                }
                if(dataInfo.goodsSpecList && dataInfo.goodsSpecList.length>0){
                    dataInfo.goodsSpecList.forEach(item=>{
                        item.marketPrice=Number(((item.marketPrice || 0) / 100).toFixed(2));
                        item.salePrice=Number(((item.salePrice || 0)/100).toFixed(2));
                        item.rebatePrice=Number(((item.rebatePrice || 0)/100).toFixed(2));
                        item.oneLevelDistributionPrice=Number(((item.oneLevelDistributionPrice || 0)/100).toFixed(2));
                        item.twoLevelDistributionPrice=Number(((item.twoLevelDistributionPrice || 0)/100).toFixed(2));
                        item.threeLevelDistributionPrice=Number(((item.threeLevelDistributionPrice || 0)/100).toFixed(2));
                        item.supplierPrice==Number(((item.supplierPrice || 0)/100).toFixed(2));
                        item.goodsWeight=Number(((item.goodsWeight || 0)/1000).toFixed(2));
                    })
                }
                //alert(dataInfo.goodsSpecList[0].goodsWeight)
                
                //多级型号表格数据拼接
                if(dataInfo.goodsModel==2){
                    this.multiModelData=dataInfo.goodsSpecList || [];
                }

                this.formData={
                    id:dataInfo.id,
                    //productLibId:dataInfo.goodsBarCodeId || '',//商品库id
                    //商品信息
                    productType:parseInt(dataInfo.goodsType) || 2,//商品类型
                    productName:dataInfo.goodsName || '',//商品名称
                    productCode:dataInfo.goodsCode || '',//商品编码
                    productGroup:dataInfo.goodsGroupId || '',//商品分组
                    productCategory: dataInfo.goodsCategoryId || '',//商品类目
                    productClassify:dataInfo.goodsClassificationId || '',//商品类型
                    productPoints:dataInfo.goodsSellingPoint || '',//商品卖点
                    imgList:dataInfo.goodsPictures || '',//商品图片
                    videoList:dataInfo.goodsVideo || '',//商品视频
                    inventoryUnit:parseInt(dataInfo.goodsUnitCode) || '',//商品库存单位（1:件数）
                    shareDescribe:dataInfo.shareDescription || '',//分享描述
                    virtualSales:dataInfo.virtualSales || '',//虚拟销量

                    //商品规格信息
                    productModel:dataInfo.goodsModel || 1,//商品型号
                    productWarning:dataInfo.goodsWarningNumber || 0,//商品预警
                    //productUnitCode:dataInfo.goodsUnitCode || 0,//库存
                    productSpecList:dataInfo.goodsSpecList || [],
                    //productMultiSpecList:dataInfo.goodsSpecList || [],

                    //物流信息
                    deliveryMode,//配送方式
                    unifiedFreight:((dataInfo.unifiedFreight || 0) / 100).toFixed(2) || '',//统一运费
                    storeReleaseChanne:1,//店铺发布渠道
                    productInfo:dataInfo.goodsDetails || '',//商品详情

                    //goodsBrandId:dataInfo.goodsBrandId||'',//品牌id
                    shopIdList:dataInfo.shopIdList||[],//渠道发布店铺id集合
                    freightTemplateId:dataInfo.freightTemplateId||[],//运费模板id
                    freightType:dataInfo.freightType||'',//快递运费

                    //多级型号
                    //modelData:deepCopy(modelData),
                    deliveryWarehouseId:dataInfo.deliveryWarehouseId || '',//发货仓库
                }

                console.log('this.formData.productSpecList',this.formData.productSpecList);
                console.log('dataInfo.goodsSpecList',dataInfo.goodsSpecList)

                //console.log('setTableDataRowSpan',this.setTableDataRowSpan(this.formData.productSpecList))
            }
        },
        //商品规格信息发生改变时触发
        handleTableChange(tableData){
            console.log(tableData);
            this.multiModelData=tableData || [];
        },
        //数据提交  //1保存商品；2保存并上架
        async submitData(){
            if(!this.formData.productName){
                this.$message.error('请输入商品名称')
                return
            }
            if(!this.formData.imgList){
                this.$message.error('请上传商品图片')
                return
            }
            if(!this.formData.productModel){
                this.$message.error('请选择商品型号')
                return
            }
            let goodsSpecList=[];
            if(this.formData.productModel==1){//统一型号
                if(!this.formData.productSpecList[0].goodsInventory && this.formData.productSpecList[0].goodsInventory!==0){
                    this.$message.error('请输入商品库存数量')
                    return
                }
                if(!this.formData.productWarning && this.formData.productWarning!==0){
                    this.$message.error('请输入商品预警')
                    return
                }
                if(this.formData.productSpecList[0].goodsInventory<this.formData.productWarning){
                    this.$message.error('商品预警不能大于商品库存数量')
                    return
                }
                if(!this.formData.productSpecList[0].marketPrice && this.formData.productSpecList[0].marketPrice!==0){
                    this.$message.error('请输入市场价格')
                    return
                }
                if(!this.formData.productSpecList[0].salePrice && this.formData.productSpecList[0].salePrice!==0){
                    this.$message.error('请输入销售价格')
                    return
                }
                if(!this.formData.productSpecList[0].rebatePrice && this.formData.productSpecList[0].rebatePrice!==0){
                    this.$message.error('请输入返利价格')
                    return
                }
                goodsSpecList=deepCopy(this.formData.productSpecList);
                goodsSpecList[0].marketPrice=Math.round((goodsSpecList[0].marketPrice || 0) * 10 * 10);
                goodsSpecList[0].salePrice=Math.round((goodsSpecList[0].salePrice || 0) * 10 * 10);
                goodsSpecList[0].rebatePrice=Math.round((goodsSpecList[0].rebatePrice || 0) * 10 * 10);
                goodsSpecList[0].oneLevelDistributionPrice=Math.round((goodsSpecList[0].oneLevelDistributionPrice || 0) * 10 * 10);
                goodsSpecList[0].twoLevelDistributionPrice=Math.round((goodsSpecList[0].twoLevelDistributionPrice || 0) * 10 * 10);
                goodsSpecList[0].threeLevelDistributionPrice=Math.round((goodsSpecList[0].threeLevelDistributionPrice || 0) * 10 * 10);
                goodsSpecList[0].supplierPrice=Math.round((goodsSpecList[0].supplierPrice || 0) * 10 * 10);
                goodsSpecList[0].goodsWeight=Math.round((goodsSpecList[0].goodsWeight || 0) * 10 * 10 * 10);
            }
            else if(this.formData.productModel==2){//多级型号  
                //this.formatModelClassify();
                goodsSpecList=deepCopy(this.multiModelData);

                if(!this.formData.productWarning && this.formData.productWarning!==0){
                    this.$message.error('请输入商品预警')
                    return
                }
                if(goodsSpecList.length>0){
                    for(let i=0;i<goodsSpecList.length;i++){
                        let item=goodsSpecList[i];
                        if(!item.isAddImg && !item.modelPicture){
                            this.$message.error('请上传规格图片')
                            return
                        }
                        if(!item.marketPrice && item.marketPrice!==0){
                            this.$message.error('请输入市场价格')
                            return
                        }
                        if(!item.salePrice && item.salePrice!==0){
                            this.$message.error('请输入销售价格')
                            return
                        }
                        if(!item.goodsInventory && item.goodsInventory!==0){
                            this.$message.error('请输入商品库存数量')
                            return
                        }
                        if(!item.rebatePrice && item.rebatePrice!==0){
                            this.$message.error('请输入返利价格')
                            return
                        }

                        item.marketPrice=Math.round((item.marketPrice || 0) * 10 * 10);
                        item.salePrice=Math.round((item.salePrice || 0) * 10 * 10);
                        item.rebatePrice=Math.round((item.rebatePrice || 0) * 10 * 10);
                        item.oneLevelDistributionPrice=Math.round((item.oneLevelDistributionPrice || 0) * 10 * 10);
                        item.twoLevelDistributionPrice=Math.round((item.twoLevelDistributionPrice || 0) * 10 * 10);
                        item.threeLevelDistributionPrice=Math.round((item.threeLevelDistributionPrice || 0) * 10 * 10);
                        item.goodsWeight=Math.round((item.goodsWeight || 0) * 10 * 10 * 10);
                    }
                }
                else {
                    this.$message.error('商品规格信息不能为空')
                    return
                }
            }
            if(!this.formData.deliveryWarehouseId){
                this.$message.error('请选择发货仓库')
                return
            }
            if(this.formData.deliveryMode.length==0){
                this.$message.error('请选择配送方式')
                return
            }
            // if(this.formData.freightType==1){//统一运费
            //     if(!this.formData.unifiedFreight){
            //         this.$message.error('统一运费不能为空')
            //         return
            //     }
            // }
            // else if(this.formData.freightType==2){//运费模板
            //     if(!this.formData.freightTemplateId){
            //         this.$message.error('运费模板不能为空')
            //         return
            //     }
            // }
            //alert(this.formData.deliveryWarehouseId)
            let params={
                //goodsBarCodeId:this.formData.productLibId,//商品条码
                goodsType:this.formData.productType,//商品类型
                goodsName:this.formData.productName,//商品名称
                goodsCode:this.formData.productCode,//商品编码
                //goodsBrandId:this.formData.goodsBrandId,   //商品品牌id
                goodsGroupId:this.formData.productGroup,//商品分组id
                goodsClassificationId:this.formData.productClassify, //商品分类id
                //goodsCategoryId:this.formData.productCategory, //商品类目id
                goodsSellingPoint:this.formData.productPoints, //商品卖点
                goodsPictures:this.formData.imgList, //商品图片多个用,隔开
                goodsVideo:this.formData.videoList, //商品视频
                shareDescription:this.formData.shareDescribe, //分享描述
                virtualSales:this.formData.virtualSales, //虚拟销量
                goodsModel:this.formData.productModel, //商品型号（1：统一型号，2：多级型号）
                goodsUnitCode:this.formData.inventoryUnit,//商品库存单位（1:件数）
                goodsWarningNumber:this.formData.productWarning, //商品预警数量
                goodsSpecList:goodsSpecList, //List<GoodsSpec>	商品规格集合
                deliveryMode:this.formData.deliveryMode?this.formData.deliveryMode.join(','):'', //发货方式（1：快递发货，2：到店自取）多个用,隔开
                freightType:this.formData.freightType, //运费类型（1：统一运费，2：运费模板）
                unifiedFreight:Math.round(this.formData.unifiedFreight * 10 * 10), //统一运费（单位：分）运费类型为1时必传
                shopIdList:this.formData.shopIdList, //渠道发布店铺id集合
                goodsDetails:this.formData.productInfo, //商品详情
                //goodsStatus:status, //商品保存状态（ 1:商品保存 2:商品保存上架 ）
                deliveryWarehouseId:this.formData.deliveryWarehouseId,//发货仓库
            }
            if(this.shopType!=2){//不是店铺分店
                params.goodsCategoryId=this.formData.productCategory;    //商品类目id
                //params.goodsUnitCode=this.formData.productUnitCode;      //商品库存单位（1:件数）
            }
            if(this.formData.freightType==2){//运费模板
                params.freightTemplateId=this.formData.freightTemplateId;//运费模板id 运费类型为2时必传
            }
            console.log(params)
            let url='/goods/repository/add';
            if(this.id){
                url= '/goods/repository/update';
                params.id=this.id;
            }
            let res = await this.$post(url, params);
            if(res && res.returnCode=='1000'){
                //this.resetData();
                console.log(this.formData,formData)
                this.$router.push({
                    name:'ProductCommodityManageCommodityLibrary'
                })
                return this.$message.success('商品保存成功！');
            }
            else{
                return this.$message.success('商品保存失败！');
            }
        },
    }
}
</script>

<style lang="less" scoped>
.title{
    font-size: 16px;
    line-height: 1.5;
    margin-bottom: 24px;
}
.desc{
    color:#ccc;
}
.table{
    border: 1px solid #E6E6E6;
    background: #fff;
    thead{
        tr{
            th{
                border: 1px solid #E6E6E6;
                white-space: nowrap;
                text-align: center;
                background:#F5F5F5;
            }
        }
    }
    tbody{
      tr:last-child{
        text-align: center;
      }
      tr{
        th,td{
          border: 1px solid #E6E6E6;
          //padding:4px 10px;
          white-space: nowrap;
          position: relative;
            text-align: center;
          .dynamic-delete-button{
            position: absolute;
            right:-0.3rem;
            top:15px;
            cursor: pointer;
          }
          input[type=text],
          input[type=number]{
            border:none;
            outline:none;
            box-sizing: border-box;
            height:40px;
          }
          input[type=number]{
            line-height: 1;
          }
        }
        th{
          input[type=text]{
            text-align: center;
          }
        }
        td{
          input[type=text],
          input[type=number]{
            // min-width:80px;
            // width:100%;
            width:100px;
          }
            .row{
                line-height: 0.6rem;
                border-bottom: 1px solid #E6E6E6;
                &:last-child{
                    border-bottom: none;
                }
            }
        }
      }
    }
    tfoot{
      td{
        background:#F5F5F5;
        text-align: center;
        a{
          font-size:12px;
        }
      }
    }
}
.flex{
    display:flex;
    align-items: center;    
    &.between{
        justify-content: space-between;
    }
    &.start{
        align-items: flex-start;
    }
}
.width100{
    width:100px;
}
.width150{
    width:150px;
}
.width200{
    width:200px;
}
.text_right{
    text-align: right;
}
.color_red{
    color:red;
}
.freightType{
    .ant-row{
        margin-bottom: 10px;
        &:last-child{
            margin-bottom: 0;
        }
    }
}
.product_picture{
    width:60px;
    height:60px;
    display: block;
}
.relative{
    position:relative;
    .delete{
        position: absolute;
        right:-40px;

    }
}
.table{
    /deep/ .ant-upload.ant-upload-select-picture-card{
        margin-bottom: 0;
        margin-right: 0;
    }
    /deep/ .ant-upload-picture-card-wrapper{
        display: block;
    }
}

</style>


